package com.itheima.web.base;


import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 通用servlet。
 * 作用：
 *    用于接收来自客户端的请求，并且根据得到的action，反射调用方法执行。
 */
public class BaseServlet extends HttpServlet {



    /**
     * 浏览器端请求的入口方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{
            //1.获取请求参数action
            String action = req.getParameter("action");//"findPage"
            //2.得到当前要访问的Servlet类的字节码
            Class servletClass = this.getClass();//this，谁触发了这个方法this就表示谁
            //System.out.println(this);
            //3.调用字节码中的方法，反射出要执行的Method对象
            Method method = servletClass.getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
            //4.解除私有限定
            method.setAccessible(true);
            //5.执行方法
            method.invoke(this,req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void printResult(HttpServletResponse response,Object obj) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        JSON.writeJSONString(response.getWriter(),obj);
    }

    public <T> T parseJSON2Object(HttpServletRequest request, Class<T> tClass) throws IOException{
        // 把表单数据之间转对象
        return JSON.parseObject(request.getInputStream(),tClass);
    }
}
